/**
 * @file colleges.js
 * @description 学院管理路由
 * @created 2024-07-01
 */

import express from 'express';
import mysql from 'mysql';
import { dbConfig } from '../config/database.js';

const router = express.Router();

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

/**
 * 获取学院列表
 * @route GET /admin/college/list
 */
router.get('/admin/college/list', async (req, res) => {
  try {
    pool.query(
      `SELECT 
        id, name, description, status, create_time as createTime
      FROM yzh_colleges
      WHERE status = 1
      ORDER BY id ASC`,
      (err, results) => {
        if (err) {
          console.error('获取学院列表失败:', err);
          return res.status(500).json({
            code: 500,
            message: '获取学院列表失败',
            error: err.message
          });
        }
        
        return res.json({
          code: 200,
          message: '获取学院列表成功',
          data: results
        });
      }
    );
  } catch (error) {
    console.error('获取学院列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取学院列表失败',
      error: error.message
    });
  }
});

/**
 * 根据学院ID获取班级列表
 * @route GET /admin/class/list-by-college/:collegeId
 */
router.get('/admin/class/list-by-college/:collegeId', async (req, res) => {
  try {
    const collegeId = req.params.collegeId;
    
    pool.query(
      `SELECT 
        c.id, c.class_code as classCode, c.name, c.grade_year as gradeYear,
        c.department_id as departmentId, c.college_id as collegeId,
        c.status, c.create_time as createTime
      FROM yzh_classes c
      WHERE c.college_id = ? AND c.status = 1
      ORDER BY c.id ASC`,
      [collegeId],
      (err, results) => {
        if (err) {
          console.error('获取班级列表失败:', err);
          return res.status(500).json({
            code: 500,
            message: '获取班级列表失败',
            error: err.message
          });
        }
        
        return res.json({
          code: 200,
          message: '获取班级列表成功',
          data: results
        });
      }
    );
  } catch (error) {
    console.error('获取班级列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取班级列表失败',
      error: error.message
    });
  }
});

export default router; 